package com.java.tutorials.designpattern.behavioral.Iterator.dveIterator;

import java.util.*;
public class IntSet {
    private Hashtable ht = new Hashtable();
    // 设计一个内部的迭代器类操纵聚集类
    public static class Iterator {
        private IntSet set;
        private Enumeration e;
        private Integer current;
        public Iterator (IntSet in) {
            set = in;
        }
        public void first () {
            e = set.ht.keys ();
            next ();
        }
        public boolean isDone () {
            return current == null;
        }
        public int currentItem () {
            return current.intValue ();
        }
        public void next () {
            try {
                current = (Integer) e.nextElement ();
            }
            catch (NoSuchElementException e) {
                current = null;
            }
        }
    }

    public void add (int in) {
        ht.put (new Integer (in), "null");
    }

    public boolean isMember (int i) {
        return ht.containsKey (new Integer (i));
    }

    public Hashtable getHashtable () {
        return ht;
    }

    //在聚集类的内部包括生成迭代器createIterator的方法
    public Iterator createIterator () {
        return new Iterator (this);
    }
}
//迭代器的应用测测试
class IteratorDemo {
    public static void main (String[] args) {
        IntSet set = new IntSet ();
        //增加成员
        for (int i = 2; i < 10; i += 2)
            set.add (i);
        //检查一下成员
        System.out.println("聚集成员检查");
        for (int i = 1; i < 9; i++)
            System.out.print (i + "-" + set.isMember (i) + " ");
        //客户请求collection对象生成多个迭代器
        IntSet.Iterator it1 = set.createIterator ();
        IntSet.Iterator it2 = set.createIterator ();
        //客户使用first(), isDone(), next(), currentItem()方法
        System.out.print ("\nIterator: ");
        for (it1.first (), it2.first (); !it1.isDone (); it1.next (), it2.next ())
            System.out.print (it1.currentItem () + " " + it2.currentItem () + " ");
        //Java习惯使用一个聚集历遍器,称为Enumeration
        System.out.print ("\nEnumeration: ");
        for (Enumeration e = set.getHashtable ().keys (); e.hasMoreElements (); )
            System.out.print (e.nextElement () + " ");
        System.out.println ();
    }
}
